package com.devMode.CommandMode;

/**
 * 命令模式
 * 将命令封装成对象
 * 1.使用命令来参数化其他对象
 * 2.将命令放入队列中排队
 * 3.将命令操作记录到日志中
 * 4.支持可撤销操作
 *
 *
 * 相当于设计一个遥控器，可以控制灯是否打开
 */
public class CommandMode {
    public static void main(String[] args) {
        Invoker invoker = new Invoker();
        Light light = new Light();
        Command lightOnCommand = new LightOnCommand(light);
        Command lightOffCommand = new LightOffCommand(light);

        invoker.setOnCommands(lightOnCommand,0);
        invoker.setOffCommands(lightOffCommand,0);

        invoker.onButtonWasPresh(0);
        invoker.offButtonWasPresh(0);
    }
}

interface Command {
    void execute();
}
class Light{
    public void on(){
        System.out.println("Light is on!!!");
    }

    public void off(){
        System.out.println("Lght is off!!!");
    }

}

class LightOnCommand implements Command {
    Light light;

    public LightOnCommand(Light light){
        this.light = light;
    }

    @Override
    public void execute() {
        this.light.on();
    }
}

class LightOffCommand implements Command {
    Light light;

    public LightOffCommand(Light light){
        this.light = light;
    }

    @Override
    public void execute() {
        this.light.off();
    }
}

class Invoker {
    private Command[] onCommands;
    private Command[] offCommands;
    private final int slotNum = 7;

    public Invoker(){
        this.onCommands = new Command[slotNum];
        this.offCommands = new Command[slotNum];
    }

    public void setOnCommands(Command command, int slot){
        onCommands[slot] = command;
    }

    public void setOffCommands(Command command, int slot){
        offCommands[slot] = command;
    }

    public void onButtonWasPresh(int slot){
        onCommands[slot].execute();
    }

    public void offButtonWasPresh(int slot){
        offCommands[slot].execute();
    }

}
